package boot

import (
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/logger"
	"github.com/kataras/iris/v12/middleware/recover"
	"reflect"
)

//新实例
type Frans struct {
	*iris.Application
	//g *iris.Handler
	g iris.Party

	db interface{}
}

//战斗>>>
func Fighting() *Frans {
	app := &Frans{Application: iris.New()}

	app.Use(logger.New())
	app.Use(recover.New())

	return app
}

//自定义^_^^_^中间件
func (this *Frans) Attach(f Onion) *Frans {
	this.Use(f.Process)
	return this
}

//控制器$$$
func (this *Frans) Action(group string, classes ...IClass) *Frans {
	this.g = this.Party(group)
	for _, clazz := range classes {
		clazz.Route(this.g) // 遍历所有IController的具体实现， 并注册Route  这才是关键 !!!

		//TODO: 采用反射注入到控制器中， 控制器中第一个嵌入属性，必须是DB
		vClass := reflect.ValueOf(clazz).Elem()
		if vClass.NumField() > 0 {
			if this.db != nil {
				vClass.Field(0).Set(reflect.New(vClass.Field(0).Type().Elem()))
				vClass.Field(0).Elem().Set(reflect.ValueOf(this.db).Elem())
			}
		}
	}

	return this
}

//设置数据库链接对象
func (this *Frans) DB(db interface{}) *Frans {
	this.db = db
	return this
}

//跑起来...
func (this *Frans) Start(ip string) {
	this.Logger().Fatal(this.Listen(ip))
}
